package com.dms.shanshan.util;

import org.hamcrest.core.Is;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

public class XMLWriter {
    public static void ReadXML(){


        try (InputStream is = new FileInputStream("D:\\dataDMS.xml")) {

            if (is == null) {
                throw new RuntimeException("文件未找到");
            }

            // 解析XML文档
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(is);

            // 使用文档对象
            System.out.println("根节点: " + doc.getDocumentElement().getNodeName());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void writeXMLByExcel(String filePath, String methodsName) throws IOException {
        Map<String, Integer> excelMap = ReadHSSFExcel.readExcel(filePath);

        try {
            // 1. 创建或加载现有XML文件
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc;

            File xmlFile = new File("D:\\dataDMS.xml");
            if (xmlFile.exists()) {
                doc = builder.parse(xmlFile);
            } else {
                doc = builder.newDocument();
                Element root = doc.createElement("data");
                doc.appendChild(root);
            }
            // 2. 确保根节点存在
            Element root = doc.getDocumentElement();
            if (root == null) {
                root = doc.createElement("data");
                doc.appendChild(root);
            }
            // 3. 创建dataBox节点
            Element dataBox = doc.createElement("dataBox");
            root.appendChild(dataBox);

            // 4. 添加methodName节点
            Element methodName = doc.createElement("methodName");
            methodName.appendChild(doc.createTextNode(methodsName));
            dataBox.appendChild(methodName);
            // 5. 添加ExcelStructure节点并填充数据
            Element excelStructure = doc.createElement("ExcelStrcture");
            dataBox.appendChild(excelStructure);
            for (Map.Entry<String, Integer> entry : excelMap.entrySet()) {
                boolean exists = false;
                NodeList items = excelStructure.getElementsByTagName("item");
                // 遍历现有节点检查重复
                for (int i = 0; i < items.getLength(); i++) {
                    Node node = items.item(i);
                    if (node.getNodeType() == Node.ELEMENT_NODE) {
                        Element existingItem = (Element) node;
                        if (entry.getKey().equals(existingItem.getAttribute("key"))) {
                            exists = true;
                            break;
                        }
                    }
                }
                if (!exists){
                Element item = doc.createElement("item");
                item.setAttribute("key", entry.getKey());
                item.setAttribute("value", entry.getValue().toString());
                excelStructure.appendChild(item);
                }
            }
            // 6. 保存修改后的XML
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(xmlFile);
            transformer.transform(source, result);

        } catch (Exception e) {
            throw new IOException("XML处理失败", e);
        }
    }
    public static Map<Map<String, Integer>, String> getXMLMap() throws ParserConfigurationException, IOException, SAXException {
        Map<Map<String, Integer>,String > resultMap = new HashMap<>();
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(new File("D:\\dataDMS.xml"));
        NodeList dataBoxList = doc.getElementsByTagName("dataBox");
        for (int i = 0; i < dataBoxList.getLength(); i++) {
            Node dataBoxNode = dataBoxList.item(i);
            if (dataBoxNode.getNodeType() == Node.ELEMENT_NODE) {
                Element dataBoxElement = (Element) dataBoxNode;
                // 获取methodName
                String methodName = dataBoxElement.getElementsByTagName("methodName")
                        .item(0).getTextContent();
                // 解析ExcelStructure
                Map<String, Integer> excelMap = new HashMap<>();
                NodeList itemList = ((Element)dataBoxElement.getElementsByTagName("ExcelStrcture")
                        .item(0)).getElementsByTagName("item");
                for (int j = 0; j < itemList.getLength(); j++) {
                    Node itemNode = itemList.item(j);
                    if (itemNode.getNodeType() == Node.ELEMENT_NODE) {
                        Element itemElement = (Element) itemNode;
                        String key = itemElement.getAttribute("key");
                        int value = Integer.parseInt(itemElement.getAttribute("value"));
                        excelMap.put(key, value);
                    }
                }
                // 添加到结果Map
                resultMap.put(excelMap, methodName);
            }
        }

        return resultMap;
    }
    public static int getRowNumByMethodName()
            throws ParserConfigurationException, IOException, SAXException {

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(new File("D:\\dataDMS.xml"));

        NodeList dataBoxList = doc.getElementsByTagName("dataBox");

        for (int i = 0; i < dataBoxList.getLength(); i++) {



        }

        // 未找到时返回-1表示不存在
        return -1;
    }
    public static int readRootRowNum() {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(new File("D://dataDMS.xml")); // XML文件路径

            // 直接获取根节点下的rowNum
            Node rowNumNode = doc.getDocumentElement()
                    .getElementsByTagName("rowNum")
                    .item(0);

            if (rowNumNode != null) {
                return Integer.parseInt(rowNumNode.getTextContent().trim());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return -1; // 未找到或解析失败时返回-1
    }

}
